var sortObj={};
var pages=document.getElementById("page");
var pageDiv=document.getElementById("pageDiv");
var mapPage=document.getElementById("mapPage");
var mapPageDiv=document.getElementById("mapPageDiv");
$(window).on("load",function () {
    if(localStorage.userId){
        $("#autoBn").prop("checked",true);
        $.post("http://localhost:8080/autoLogin",{
            id:localStorage.userId
        },function (res) {
            $("#loginBn").hide();
            $("#adduserBn").hide();
            $("#user").show().text(res);
            $("#logoutBn").show();
        });
    }
});
/*回到顶部*/
$(window).on("scroll",function (e) {
    if($(this).scrollTop()>=50){
        $("#top").show();
    }else {
        $("#top").hide();
    }
});
/*地图*/
function createMap(storeArr) {
    /*引入地图*/
    var map = new AMap.Map('container',{
        resizeEnable: true,
        zoom: 10,
        center: [116.480983, 40.0958]
    });
    /*地图工具栏*/
    AMap.plugin(['AMap.ToolBar','AMap.Scale','AMap.OverView'], function(){
        map.addControl(new AMap.ToolBar());
        map.addControl(new AMap.Scale());
        map.addControl(new AMap.OverView({isOpen:true}));
    });
    /*搜索栏*/
    AMap.plugin('AMap.Autocomplete',function(){//回调函数
        //实例化Autocomplete
        var autoOptions = {
            city: "010", //城市，默认全国
            input:"search"//使用联想输入的input的id
        };
        autocomplete= new AMap.Autocomplete(autoOptions);
        //TODO: 使用autocomplete对象调用相关功能
        AMap.event.addListener(autocomplete, "select", function(){
            //TODO 针对选中的poi实现自己的功能
        });
    });

    console.log(storeArr);
    for(var i=0;i<storeArr.length;i++){
        marker = new AMap.Marker({
            //标记位置经纬度[经度，纬度]
            position: [storeArr[i]["map_longitude"],storeArr[i]["map_latitude"]],
            //鼠标悬停标记的信息
            title: storeArr[i]["shop_name"],
            //指向标记所在的地图
            map: map,
            //改变图标样式
            icon:"image/icon1.png"
        });
        showinfomessage(i);
        //实例化信息窗体
        function showinfomessage(i) {
            var title=storeArr[i]["shop_name"], content=[];
            content.push("主营："+storeArr[i]['main']);
            content.push("地址："+storeArr[i]['addr_detail']);
            var infoWindow = new AMap.InfoWindow({
                isCustom: true,  //使用自定义窗体
                content: createInfoWindow(title,content.join("<br>")),
                offset: new AMap.Pixel(16, -50)//-113, -140
            });

            AMap.event.addListener(marker,"click",clickHandler);
            function clickHandler(e) {
                // console.log(e);
                infoWindow.open(map, [storeArr[i]["map_longitude"],storeArr[i]["map_latitude"]]);
            }
        }

    }

}
/*创建信息窗体*/
function createInfoWindow(title,content) {
    return "<div class='info'>" +
        "<h3>"+title+"<span class='closeMsg' onclick='closeMsg()'>×</span></h3>" +
        "<p>"+content+"</p>" +
        "<div class='info_b'><img src='http://webapi.amap.com/images/sharp.png'></div>" +
        "</div>"
}
/*关闭信息窗体*/
function closeMsg() {
    $(".info").hide();
}
/*轮播图*/
var mySwiper=new Swiper(".swiper-container",{
    //方向:垂直vertical，水平horizontal
    direction:"horizontal",
    //是否循环
    loop:true,
    //分页器
    pagination:".swiper-pagination",
    //自动轮播
    autoplay:2000
});
getHotPhone();
getYouXuan();
getGoodPj();
getAllStore("",pages,mapPage);
//        $("#default");
/*点击地图模式*/
$("#mapBn").click(function () {
    $("#mapDiv").show();
});
$("#closeMap").click(function () {
    $("#mapDiv").hide();
});
/*排序按钮*/
$("#default").css({
    color:"green",
    border:"1px solid #cccccc"
}).click(function () {
    $(this).css({
        color:"green",
        border:"1px solid #cccccc"
    }).next().css({
        color:"#000000",
        border:"none"
    }).next().css({
        color:"#000000",
        border:"none"
    });
    $("#mapPage").remove();
    var pageMap=document.createElement("ul");
    mapPageDiv.appendChild(pageMap);
    pageMap.id="mapPage";
    $("#page").remove();
    var pages=document.createElement("ul");
    pageDiv.appendChild(pages);
    pages.id="page";
    getAllStore("",pages,pageMap);
});
$("#count").click(function () {
    $(this).css({
        color:"green",
        border:"1px solid #cccccc"
    }).next().css({
        color:"#000000",
        border:"none"
    }).prev().prev().css({
        color:"#000000",
        border:"none"
    });
    $("#mapPage").remove();
    var pageMap=document.createElement("ul");
    mapPageDiv.appendChild(pageMap);
    pageMap.id="mapPage";
    $("#page").remove();
    var pages=document.createElement("ul");
    pageDiv.appendChild(pages);
    pages.id="page";
    getAllStore("count",pages,pageMap);
});
$("#visit").click(function () {
    $(this).css({
        color:"green",
        border:"1px solid #cccccc"
    }).prev().css({
        color:"#000000",
        border:"none"
    }).prev().css({
        color:"#000000",
        border:"none"
    });
    $("#mapPage").remove();
    var pageMap=document.createElement("ul");
    mapPageDiv.appendChild(pageMap);
    pageMap.id="mapPage";
    $("#page").remove();
    var pages=document.createElement("ul");
    pageDiv.appendChild(pages);
    pages.id="page";
    getAllStore("shop_visit",pages,pageMap);
});
/*获取所有商铺信息*/
function getAllStore(type,elem,mapP) {
    $.get("http://localhost:8080/sort",{
        type:type
    },function (res) {
//                console.log(res);
        /*商铺分页*/
        var pagePlugin=new PagePlugin(elem,{
            showPageCount:10,
            showMsgCount:5,
            allMsgCount:res.length,
            pageBtnStyle:"active",
            backFn:function (page,count) {
                var showMsgArr=res.slice((page-1)*count,page*count);
//                        console.log(showMsgArr);
                sortObj.arr=showMsgArr;
                $("#list").html(baidu.template("sortList",sortObj));
                showStore();
//                        enterStore();
            }
        });

        /*地图分页*/
        var pageP=new PagePlugin(mapP,{
            showPageCount:10,
            showMsgCount:5,
            allMsgCount:res.length,
            pageBtnStyle:"active",
            backFn:function (page,count) {
                var showMsgArr=res.slice((page-1)*count,page*count);
//                        console.log(showMsgArr);
                if($("#container")) {
                    $("#container").remove();
                }
                $("<div id='container'></div>").insertAfter($(".topMap"));
                createMap(showMsgArr);
            }
        });
    });
}
/*获取所有商家好评榜*/
function getGoodPj() {
    $.get("http://localhost:8080/comments",{},function (res) {
//                console.log(res);
        var obj={};
        obj.arr=res;
        $("#listShop").html(baidu.template("storeEvaluate",obj));
    });
}
/*滑过显示进入店铺*/
function showStore() {
    $.each($("#list").children("li"),function (index,item) {
        $(item).on("mouseover mouseout",function (e) {
            if(e.type=="mouseover"){
                $(item).css("background","#f7f7f7").children("a").show();
            }else if(e.type=="mouseout"){
                $(item).css("background","#ffffff").children("a").hide();
            }
        });
    });
}
/*点击进入店铺按钮*/
function enterStore(id) {
    localStorage.shopId=id;
    window.open("html/shop.html");
}
/*获取热门手机回收信息*/
function getHotPhone() {
    $.get("http://localhost:8080/src/data/shoujihuishou.json",{},function (res) {
//                console.log(res);
        var obj={};
        obj.arr=res.result;
        $("#hPList").html(baidu.template("hotPhone",obj));
    });
}
/*获取优品精选信息*/
function getYouXuan() {
    $.get("http://localhost:8080/src/data/youpinjingxuan.json",{},function (res) {
//                console.log(res);
        var obj={};
        obj.arr=res.result;
        $("#youList").html(baidu.template("ypTp",obj));
    });
}
var obj={};
/*点击城市列表*/
$("#cutCityBn").click(function () {
    $("#cityDiv").show();
    getAllCity();
});
$("#cityCloseBn").click(function () {
    $("#cityDiv").hide();
});
/*点击登录*/
$("#loginBn").click(function () {
    $(".loginDiv").show();
    getYzm();
});
$("#loginBnQ").click(login);
/*登录*/
function login() {
    $.post("http://localhost:8080/login",{
        user:$("#loginN").val(),
        pass:$("#loginPwd").val()
    },function (res) {
        console.log(res);
        if(res=="1"){
            $(".loginDiv").hide();
            $("#loginBn").hide();
            $("#adduserBn").hide();
            $("#user").text($("#loginN").val()).show();
            $("#loginB").children("p").children("input").val("");
            $("#logoutBn").show();
        }else{
            $("#loginBnQ").next().text("登录失败");
        }
    });
}
/*点击自动登录*/
$("#autoBn").click(function () {
    if($(this).prop("checked")==true){
        $.post("http://localhost:8080/oneUser",{
            user:$("#loginN").val(),
            pass:$("#loginPwd").val()
        },function (res) {
            console.log(res);
            localStorage.userId=res;
        });
    }else {
        localStorage.removeItem("userId");
        console.log(localStorage.userId);
    }
});
$("#logoutBn").click(function () {
    $.post("http://localhost:8080/logout",{},function (res) {
        console.log(res);
        $("#loginBn").show();
        $("#adduserBn").show();
        $("#user").text("").hide();
        $("#logoutBn").hide();
    });
});
/*点击立即登录*/
$("#qAddUser").click(function () {
    $(".addUserDiv").hide();
    $(".loginDiv").show();
});
/*点击注册*/
$("#adduserBn").click(function () {
    $(".addUserDiv").show();
    getYzm();
});
/*关闭注册*/
$("#closeAddUser").click(function () {
    $(".addUserDiv").hide();
});
/*关闭登录页面*/
$("#closeLoginBn").click(function () {
    $(".loginDiv").hide();
});
/*获取所有城市信息*/
function getAllCity() {
    $.get("http://localhost:8080/src/data/city.json",{},function (res) {
        console.log(res);
        obj.hotArr=res.result.hotcity;
        obj.cityObj=res.result.citylist;
        $("#hotCity").html(baidu.template("hotTp",obj));
        $("#pinyinList").html(baidu.template("pinyinTp",obj));
        pinyin("A");
    });
}
/*点击拼音*/
function pinyin(k) {
    var pinyinObj={};
    pinyinObj.arr=obj.cityObj[k];
    $("#cityList").html(baidu.template("cityTp",pinyinObj));
}
/*显示城市*/
function cityView(city) {
    $("#cityView").text(city);
}
/*验证手机号*/
$("#tel").on("blur",function () {
    if($(this).val()==""){
        $("#tel").next().text("请输入手机号码");
        return;
    }
    $.get("http://localhost:8080/blurTel",{
        tel:$("#tel").val()
    },function (res) {
        console.log(res);
        $("#tel").next().text(res);
    });
});
/*验证码*/
$("#yzmBn").click(getYzm);
$("#yzmLBn").click(getYzm);
function getYzm() {
    $.get("http://localhost:8080/getYzm",{},function (res) {
        console.log(res);
        $("#yzmBn").prev().text(res);
        $("#yzmLBn").prev().text(res);
    });
}
$("#yzm").on("blur",function () {
    if($("#yzm").val()==$("#yzm").next().text()){
        $("#yzmBn").next().text("√");
    }
});
$("#yzmL").on("blur",function () {
    if($("#yzmL").val()==$("#yzmL").next().text()){
        $("#yzmLBn").next().text("√");
    }
});
$("#jymBn").click(function () {
    if($("#tel").val()=="" && $("#yzm").val()==""){
        $("#jymBn").prop("disabled");
        return;
    }else {
        $("#jymBn").removeProp("disabled");
    }
    getJym();
});
/*获取校验码*/
function getJym() {
    $.post("http://localhost:8080/getJym",{
        tel:$("#tel").val(),
        time:(new Date()).getTime()
    },function (res) {
        console.log(res);
        $("#jym").val(res);
    });
}
/*点击选中按钮*/
$("#checks").click(function () {
    if($(this).prop("checked")==false){
        $("#addUser").attr("disabled","disabled");
    }else if($(this).prop("checked")==true){
        $("#addUser").removeAttr("disabled");
    }
});
$("#addUser").click(addUser);
/*注册*/
function addUser() {
    $.post("http://localhost:8080/addUser",{
        tel:$("#tel").val(),
        time:(new Date()).getTime(),
        jym:$("#jym").val(),
        pwd:$("#pwd").val()
    },function (res) {
        console.log(res);
        if(res=="0"){
            $("#addUser").next().text("验证码超时");
        }else if(res=="1"){
            $("#addUser").next().text("注册成功");
            $(".addUserDiv").hide();
            $("#telDiv").children("p").children("input").val("");
        }else if(res=="-1"){
            $("#addUser").next().text("验证码错误");
        }
    });
}
